// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a'
}) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  
  try {
    // 验证管理员身份
    const result = await cloud.callFunction({
      name: 'checkAdminAuth',
      data: {
        adminId: event.adminId || '',
        token: event.token || ''
      }
    })
    
    const { code, data } = result.result
    
    if (code !== 0 || !data) {
      return {
        code: 401,
        data: null,
        message: '未授权访问'
      }
    }
    
    // 参数验证
    if (!event.equipmentId) {
      return {
        code: -1,
        data: null,
        message: '装备ID不能为空'
      }
    }
    
    // 检查集合是否存在
    try {
      const collections = await db.listCollections().get();
      const collectionList = collections.data.map(col => col.name);
      
      if (!collectionList.includes('equipment')) {
        return {
          code: -1,
          data: null,
          message: '装备集合不存在'
        }
      }
      
      if (!collectionList.includes('orders')) {
        await db.createCollection('orders');
      }
    } catch (error) {
      console.error('检查集合失败:', error);
    }
    
    // 检查装备是否被借用
    const { total } = await db.collection('orders').where({
      equipmentId: event.equipmentId,
      status: '借用中'
    }).count()
    
    if (total > 0) {
      return {
        code: -1,
        data: null,
        message: '该装备有用户正在借用，无法删除'
      }
    }
    
    // 删除装备
    await db.collection('equipment').doc(event.equipmentId).remove()
    
    return {
      code: 0,
      data: null,
      message: '删除装备成功'
    }
  } catch (err) {
    return {
      code: 500,
      data: null,
      message: '删除装备失败: ' + err.message
    }
  }
} 